package com.simplehire.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TongyiService implements AIService {
    private static final Logger logger = LoggerFactory.getLogger(TongyiService.class);

    @Value("${tongyi.api.key}")
    private String apiKey;

    private final String apiUrl;
    private final WebClient webClient;
    private final ObjectMapper objectMapper;

    public TongyiService(WebClient.Builder webClientBuilder,
                         ObjectMapper objectMapper,
                         @Value("${tongyi.api.url}") String apiUrl) {
        this.apiUrl = apiUrl;
        this.webClient = webClientBuilder
                .baseUrl("") // 设置为空，使用完整URL
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();
        this.objectMapper = objectMapper;

        logger.info("通义千问服务初始化完成，API URL: {}", apiUrl);
    }

    @Override
    public String analyzeResume(String resumeText) {
        logger.info("使用通义千问模型分析简历，文本长度: {}", resumeText.length());

        String prompt = String.format("""
            请以专业HR面试官的身份，基于以下简历内容完成三个任务：
            
            简历内容：
            %s
            
            具体要求：
            1. 生成3个针对性的面试问题（与候选人背景匹配）
            2. 给出综合评分（100分制）并说明评分依据
            3. 提供3条实用的简历优化建议
            
            请用中文分点回答，不需要JSON格式。
            """, resumeText);

        return callTongyiAPI(prompt);
    }

    @Override
    public String continueConversation(String resumeText, String conversationHistory, String userMessage) {
        logger.info("通义千问模型继续对话，用户消息: {}", userMessage);

        // 构建对话消息列表
        List<Map<String, String>> messages = new ArrayList<>();

        // 系统提示
        messages.add(Map.of(
                "role", "system",
                "content", "你是专业的HR面试助手，负责基于候选人简历进行面试交流。请保持专业、礼貌的态度，可以提出问题、给予反馈或提供建议。"
        ));

        // 添加简历信息
        messages.add(Map.of(
                "role", "system",
                "content", "候选人简历内容：\n" + resumeText
        ));

        // 解析历史对话
        if (conversationHistory != null && !conversationHistory.trim().isEmpty()) {
            String[] lines = conversationHistory.split("\n\n");
            for (String line : lines) {
                if (line.startsWith("我:")) {
                    String content = line.substring(2).trim();
                    messages.add(Map.of("role", "user", "content", content));
                } else if (line.contains("面试辅助:")) {
                    int colonIndex = line.indexOf(":");
                    if (colonIndex > 0) {
                        String content = line.substring(colonIndex + 1).trim();
                        messages.add(Map.of("role", "assistant", "content", content));
                    }
                }
            }
        }

        // 添加当前用户消息
        messages.add(Map.of("role", "user", "content", userMessage));

        return callTongyiAPIMulti(messages);
    }

    @Override
    public String getModelName() {
        return "tongyi";
    }

    /**
     * 调用通义千问API处理单轮对话
     */
    private String callTongyiAPI(String prompt) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "qwen-plus"); // 通义千问模型名称，根据实际情况调整
        requestBody.put("messages", List.of(Map.of("role", "user", "content", prompt)));
        requestBody.put("temperature", 0.7);
        requestBody.put("max_tokens", 2000);

        return callAPI(requestBody);
    }

    /**
     * 调用通义千问API处理多轮对话
     */
    private String callTongyiAPIMulti(List<Map<String, String>> messages) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "qwen-plus"); // 通义千问模型名称，根据实际情况调整
        requestBody.put("messages", messages);
        requestBody.put("temperature", 0.7);
        requestBody.put("max_tokens", 2000);

        return callAPI(requestBody);
    }

    /**
     * 通用API调用方法
     */
    private String callAPI(Map<String, Object> requestBody) {
        try {
            logger.info("调用通义千问API，URL: {}", apiUrl);
            logger.debug("请求参数: {}", requestBody);

            String response = webClient.post()
                    .uri(apiUrl)
                    // 修改认证头为Authorization: Bearer <API_KEY>格式
                    .header(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                    .bodyValue(requestBody)
                    .retrieve()
                    .onStatus(status -> status.isError(), clientResponse -> {
                        logger.error("通义千问API调用失败，状态码: {}", clientResponse.statusCode());
                        return clientResponse.bodyToMono(String.class)
                                .flatMap(errorBody -> {
                                    logger.error("通义千问API错误响应: {}", errorBody);
                                    return Mono.error(new RuntimeException("通义千问API错误: " + clientResponse.statusCode() + " - " + errorBody));
                                });
                    })
                    .bodyToMono(String.class)
                    .block();

            logger.debug("通义千问API原始响应: {}", response);
            return parseAPIResponse(response);

        } catch (Exception e) {
            logger.error("通义千问API调用异常", e);
            return "通义千问模型调用失败: " + e.getMessage();
        }
    }

    /**
     * 解析通义千问API响应
     */
    private String parseAPIResponse(String response) {
        try {
            if (response == null || response.trim().isEmpty()) {
                logger.error("通义千问API返回空响应");
                return "通义千问API返回空响应";
            }

            JsonNode rootNode = objectMapper.readTree(response);
            logger.debug("解析后的JSON响应: {}", rootNode.toString());

            // 处理错误响应
            if (rootNode.has("error")) {
                String errorMsg = rootNode.get("error").get("message").asText("未知错误");
                logger.error("通义千问API返回错误: {}", errorMsg);
                return "通义千问API错误: " + errorMsg;
            }

            // 解析正常响应
            JsonNode choices = rootNode.get("choices");
            if (choices != null && choices.isArray() && choices.size() > 0) {
                JsonNode message = choices.get(0).get("message");
                if (message != null && message.has("content")) {
                    String content = message.get("content").asText();
                    logger.info("成功解析通义千问API响应，内容长度: {}", content.length());
                    return content;
                }
            }

            // 尝试其他可能的响应格式
            if (rootNode.has("output")) {
                JsonNode output = rootNode.get("output");
                if (output.has("text")) {
                    String text = output.get("text").asText();
                    logger.info("使用output.text字段，内容长度: {}", text.length());
                    return text;
                }
            }

            logger.error("无法解析通义千问API响应格式: {}", response);
            return "无法解析通义千问API响应: " + response;

        } catch (Exception e) {
            logger.error("解析通义千问API响应失败", e);
            return "解析通义千问响应出错: " + e.getMessage();
        }
    }

    /**
     * 测试通义千问API连接
     */
    public String testConnection() {
        try {
            String response = callTongyiAPI("你好，请回复'通义千问连接成功'");
            return "通义千问测试: " + response;
        } catch (Exception e) {
            return "通义千问测试失败: " + e.getMessage();
        }
    }

    public String getApiKey() {
        return apiKey;
    }

    public String getApiUrl() {
        return apiUrl;
    }
}